/*
* This class scope is to zip the log file folders and send a mail copy to admin.
* Modified by : Basha (02/07/2003)
*/

package com.scalar.chiptrack.jobs.systemjobs;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.scalar.ScalarException;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.users.dao.NotificationSetupDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;


public final class CollectAdaptorLogsJob extends JobHandler implements FilenameFilter 
{
    private static final String LOCK_FILES_EXTENSION = ".lck";
    private static final int BUFFER = 2048;

    /**
     * Overwrites execute() in JobHandler class
     */
    public void execute() 
    {
        try 
		{
            String from = ConfigManager.getSysAdminEmail();
            String to 	= NotificationSetupDAO.loadAdaptorNotificationSubscriberEmails();
            
            if( ( from == null ) || ( from.trim().length() == 0 ) ) 
            {
                throw new ScalarException ( "AdaptroLogs Collector: System Admin Mail Property is not defined in scalar.properties" );
            }

            if( ( to == null ) || ( to.trim().length() == 0 ) ) 
            {
                throw new ScalarException  ("AdaptorLogs Collector: There are no subscribers to send adaptor logs.. ");
            }

            ArrayList zipArrayList = new ArrayList();

            /*String umcDirName = AdaptorUtils.getUMCDataOutputDir();

            if(umcDirName != null)
            {
                umcDirName = (umcDirName.trim())+"/logs";
                File umcLogsDir = new File (umcDirName.trim());
                if (umcLogsDir.exists()) {
                    //System.out.println("If UMC Dir exists");

                        String zipFile = ((umcDirName.trim())+"/"+(getTimeStamp())+"_umc.zip").trim();
                        String filePath = umcDirName.trim();

                        zipArrayList.add(fileZipping(zipFile,filePath));
                }
            }*/

            //System.out.println("Satage1");

            //System.out.println("ASEA DIR NAME:"+AdaptorUtils.getASEADataOutputDir());

            /*String aseaDirName = AdaptorUtils.getASEADataOutputDir();

            if(aseaDirName != null)
            {
                aseaDirName = aseaDirName.trim()+"/logs";
                File aseaLogsDir = new File(aseaDirName.trim());
                if (aseaLogsDir.exists()) {
                    //System.out.println("If ASEA Dir exists");

                        String zipFile = ((aseaDirName.trim())+"/"+(getTimeStamp())+"_asea.zip").trim();
                        String filePath = aseaDirName.trim();

                        zipArrayList.add(fileZipping(zipFile,filePath));
                }
            }*/

            //System.out.println("Satage2");

            /*String asetDirName = AdaptorUtils.getASETDataOutputDir();

            if(asetDirName != null)
            {
                asetDirName = asetDirName.trim()+"/logs";
                File asetLogsDir = new File(asetDirName.trim());
                if (asetLogsDir.exists()) {
                    //System.out.println("If ASET Dir exists");

                        String zipFile = ((asetDirName.trim())+"/"+(getTimeStamp())+"_aset.zip").trim();
                        String filePath = asetDirName.trim();

                        zipArrayList.add(fileZipping(zipFile,filePath));
                }
            }*/

            //System.out.println("Satage3");

            Object[] obj = zipArrayList.toArray();
		    int size = obj.length;
		    String[] Logs = new String[size];

            //System.out.println("Satage4");

            for(int i=0;i<size;i++){
			    Logs[i] = obj[i].toString();
		    }

            //System.out.println("Satage5");
            //System.out.println("Length of zipLog:"+Logs.length);


            if (Logs.length != 0) {
                String subject = "Log Files";

                //String message = "Hai ! This is for testing --- cheers Basha";
                //Mailer.send (from, to, null/*cc*/, null/*bcc*/, subject, message, Logs);
                Mailer.send (from, to, null/*cc*/, null/*bcc*/, subject, null /*message*/, Logs);
                System.out.println ("done : Mail has been send :Collect AdaptorLogsJob");
            }
        }
        catch (Exception e) {
            System.out.println ("Exception while trying to send adaptor logs for review: " + e);
            e.printStackTrace();
        }
    }


    // For testing purpose only
    public static void main (String[] args) {
        new CollectAdaptorLogsJob().execute();
    }


    // from FilenameFilter interface
    public boolean accept (File parentDir, String fileName) {

        if (fileName == null) return false;

        return !fileName.endsWith (LOCK_FILES_EXTENSION);
    }

    // The scope of this method is to zip the files for a given directory
    public String fileZipping(String zipFile,String filePath) 
    {
        ZipOutputStream zos = null;
        int search = 0;

        try
		{
            byte data[] 	= new byte[BUFFER];
            File file 		= new File(filePath);
			String files[] 	= file.list();
            int lint_fileCount 		= files.length;
            BufferedInputStream bis = null;

             for( int i = 0; i < lint_fileCount; i++ )
			 {
                 if( !( files[i].endsWith( ".zip" ) || files[i].endsWith( ".lck" ) ) )
                 {
                     FileInputStream fis = new FileInputStream( filePath+"/"+files[i] );
                     bis = new BufferedInputStream( fis, BUFFER );

                     ZipEntry entry = new ZipEntry( files[i] );
  
                     if( search == 0 )
                     {
                     	FileOutputStream fos = new FileOutputStream( zipFile );
                        zos = new ZipOutputStream( new BufferedOutputStream( fos ) );
                        search = 1;
                     }
                     zos.putNextEntry( entry );

                     int count;
                     while( ( count = bis.read( data, 0, BUFFER ) ) != -1 )
                     {
                        zos.write( data, 0, count );
                     }
                     bis.close();
                 }
			 }
        }
        catch(Exception e){
             System.out.println("fileZipping Exception:"+e);
        }
        finally
		{
            try
			{
                if(zos != null)
                zos.close();
            }
            catch(Exception e){
            }
        }
        return zipFile;
    }

    public String getTimeStamp(){
        String timeStamp = ((DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM).format(new Date())));
        timeStamp = timeStamp.replace(':','_');
		timeStamp = timeStamp.replace(',','_');
		timeStamp = timeStamp.replace(' ','_');

        return timeStamp;
    }
}